package test_system.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import test_system.menu.Menu;
import test_system.parser.*;
import test_system.questions.*;
import test_system.user_logic.*;

public class TestController {

    public static TestWrapper test;
    public static Session userSession;
    private String QUESTION_FILE = "questions.txt";

    public void startTest() {
        Menu menu = new Menu();
        userSession = menu.avtorization();
        //menu.adminMenu();
        UserAnswers userAnswers = new UserAnswers(getTestAnswers());
        menu.markOutput(userAnswers);
    }

    ArrayList<Answer> getTestAnswers() {
        ArrayList<Answer> userAnswers;
        if (isExistRestoreFile()) {
            userAnswers = getRestoreTestAnswers();
        } else {
            userAnswers = getNewTestAnswers();
        }
        return userAnswers;
    }

     ArrayList<Answer> getRestoreTestAnswers() {
        Menu menu = new Menu();
        SessionRestore restorer = new SessionRestore();
        RestoreInfo info = restorer.restore(userSession.getUser().getLogin() + ".txt");
        test = info.getTest();
        ArrayList<Answer> userAnswers = replaseAnswers(info.getUserAnswers());
        userAnswers = menu.getUserAnswers(userAnswers, info.getUserAnswers().size() - 1);
        return userAnswers;
    }

     ArrayList<Answer> getNewTestAnswers() {
        Menu menu = new Menu();
        StringBuffer testData = new ParserCSV().parseFile(QUESTION_FILE);
        test = new ParseRefactor().createTest(testData);
        ArrayList<Answer> userAnswers = new ArrayList<Answer>();
        userAnswers = menu.getUserAnswers(userAnswers, 0);
        return userAnswers;
    }

     ArrayList<Answer> replaseAnswers(ArrayList<Answer> oldAnsw) {
        ArrayList<Answer> newAnsw = new ArrayList<Answer>(oldAnsw);
        Collections.copy(newAnsw, oldAnsw);
        return newAnsw;
    }

     boolean isExistRestoreFile() {
        String fileName = userSession.getUser().getLogin() + ".txt";
        File file = new File(fileName);
        return file.exists();
    }

}
